package io.coderyeah.ymcc.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import io.coderyeah.ymcc.domain.CourseMarket;
import io.coderyeah.ymcc.domain.CourseUserLearn;
import io.coderyeah.ymcc.dto.PayResultMsgInMQ;
import io.coderyeah.ymcc.mapper.CourseUserLearnMapper;
import io.coderyeah.ymcc.service.ICourseMarketService;
import io.coderyeah.ymcc.service.ICourseUserLearnService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author coderyeah
 * @since 2022-10-23
 */
@Service
public class CourseUserLearnServiceImpl extends ServiceImpl<CourseUserLearnMapper, CourseUserLearn> implements ICourseUserLearnService {
    @Autowired
    private ICourseMarketService marketService;

    @Override
    public void updateUserLearn(PayResultMsgInMQ payResultMsgInMQ) {
        Map map = JSON.parseObject(payResultMsgInMQ.getExtParams(), Map.class);
        Long userId = Long.valueOf(map.get("userId").toString());
        String[] ids = map.get("courseIds").toString().split(",");
        for (String id : ids) {
            //查询用户是否购买过此课程
            Wrapper<CourseUserLearn> wrapper = new EntityWrapper<>();
            wrapper.eq("login_id", userId);
            wrapper.eq("course_id", id);
            CourseUserLearn courseUserLearn = selectOne(wrapper);
            //查询用户购买课程有效期+
            CourseMarket courseMarket = marketService.selectById(id);
            //计算当前课程的结束时间
            Date date = DateUtils.addDays(new Date(), courseMarket.getValidDays());

            if (courseUserLearn != null) {
                //买过课程当前是否过期
                if (new Date().before(courseUserLearn.getEndTime())) {//没有过期
                    date = DateUtils.addDays(courseUserLearn.getEndTime(), courseMarket.getValidDays());
                }
                courseUserLearn.setEndTime(date);
                courseUserLearn.setState(0);
                updateById(courseUserLearn);
            } else {
                courseUserLearn = new CourseUserLearn();
                courseUserLearn.setLoginId(userId);
                courseUserLearn.setStartTime(new Date());
                //end_time
                courseUserLearn.setEndTime(date);
                courseUserLearn.setState(0);
                courseUserLearn.setCourseId(Long.valueOf(id));
                courseUserLearn.setCourseOrderNo(payResultMsgInMQ.getOrderSn());
                courseUserLearn.setCreateTime(new Date());
                insert(courseUserLearn);
            }
        }
    }
}
